package com.bungarus.group.model;

import com.bungarus.group.cachestore.CacheStore;
import com.bungarus.group.cachestore.CacheTransformer;
import com.bungarus.group.cachestore.StoreColumn;
import com.bungarus.group.cachestore.StoreRow;
import org.springframework.stereotype.Component;

import java.util.LinkedHashSet;
import java.util.Set;

@Component
public class GroupCacheTransformer implements CacheTransformer<Group> {
    private static final String NAME = "group";
    private static final String GROUP_NAME = "_g_";
    private static final String GROUP_ID = "_gid_";
    private static final String TENANT_ID = "_tid_";

    @Override
    public String getCacheTableName() {
        return NAME;
    }

    @Override
    public StoreRow transform(Group group) {
        Set<StoreColumn> columns = new LinkedHashSet<>();

        StoreColumn column = new StoreColumn();
        column.setColumnName(GROUP_NAME);
        column.setColumnValue(group.getName());
        columns.add(column);

        column = new StoreColumn();
        column.setColumnName(GROUP_ID);
        column.setColumnValue(String.valueOf(group.get_id()));
        columns.add(column);

        column = new StoreColumn();
        column.setColumnName(TENANT_ID);
        column.setColumnValue(String.valueOf(group.getTenantId()));
        columns.add(column);

        StoreRow row = StoreRow.newBuilder()
                .id(CacheStore.ofUniqueId(String.valueOf(group.getTenantId()), String.valueOf(group.get_id())))
                .table(getCacheTableName())
                .values(columns)
                .build();

        return row;
    }

    @Override
    public Group reverse(StoreRow row) {
        Set<StoreColumn> columns = row.getRowValues();
        Group.Builder builder = Group.newBuilder();
        columns.forEach(column -> {
            if(column.getColumnName().equals(GROUP_NAME)) {
                builder.name(column.getColumnValue());
            }
            else if(column.getColumnName().equals(GROUP_ID)) {
                builder.id(Long.valueOf(column.getColumnValue()));
            }
            else if(column.getColumnName().equals(TENANT_ID)) {
                builder.tenant(Long.valueOf(column.getColumnValue()));
            }
            else
                throw new IllegalStateException();
        });
        return builder.build();
    }
}
